<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { saveRole, updateRole } from "@/api/system.ts";
import { ApiResult } from "@/util/request";

interface IDate {
  id: string;
  roleCode: string;
  roleName: string;
  sort: string;
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object,
    default: () => {},
  },
});

const emit = defineEmits(["update:visible", "update:data", "submit"]);

const ruleFormRef = ref();
const submitLoading = ref<boolean>(false);

const formData = reactive<IDate>({
  id: "",
  roleCode: "",
  roleName: "",
  sort: "",
});

const rules = reactive<FormRules<IDate>>({
  roleCode: [{ required: true, message: "请输入", trigger: "blur" }],
  roleName: [{ required: true, message: "请输入", trigger: "blur" }],
  sort: [{ required: true, message: "请输入", trigger: "blur" }],
});

const dialogVisible = computed({
  get() {
    return props.visible;
  },

  set(visible: boolean) {
    emit("update:visible", visible);
  },
});

const title = computed(() => {
  return formData?.id ? "编辑角色" : "新增角色";
});

function closeDialog() {
  resetForm(ruleFormRef.value);
  emit("update:visible", false);
  emit("update:data", null);
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    let result: ApiResult<any>;
    if (valid) {
      submitLoading.value = true;
      if (formData?.id) {
        result = await updateRole(formData);
      } else {
        result = await saveRole(formData);
      }
      const { success, msg } = result;
      submitLoading.value = false;
      if (!success) {
        ElMessage.error(msg);
        return;
      }
      closeDialog();
      emit("submit");
    } else {
      console.log("error submit!", fields);
    }
  });
};

watch(dialogVisible, (visible) => {
  Object.keys(formData).forEach((key: any) => {
    formData[key as keyof IDate] = visible ? props.data?.[key] ?? "" : "";
  });
});
</script>

<template>
  <el-dialog
    @close="closeDialog"
    v-model="dialogVisible"
    :title="title"
    width="30%"
  >
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="formData.roleName" />
      </el-form-item>
      <el-form-item label="CODE" prop="roleCode">
        <el-input v-model="formData.roleCode" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" :max="999" />
      </el-form-item>
    </el-form>
    <div class="footer">
      <el-button
        @click="submitForm(ruleFormRef)"
        type="primary"
        :loading="submitLoading"
      >
        保存
      </el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.footer {
  width: 100%;
  text-align: center;
  margin-top: 50px;
}
</style>
